package com.itcast.gameforum.controller;

import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itcast.gameforum.common.dto.LoginDto;
import com.itcast.gameforum.common.dto.RegisterDto;
import com.itcast.gameforum.common.lang.Result;
import com.itcast.gameforum.entity.User;
import com.itcast.gameforum.service.UserService;
import com.itcast.gameforum.shiro.JwtToken;
import com.itcast.gameforum.util.JwtUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import javax.validation.Valid;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

@RestController
@RequestMapping("/user/")
public class UserController {

    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    JwtUtils jwtUtils;
    @Autowired
    UserService userService;


    //用户登录
    @CrossOrigin
    @PostMapping("login")
    public Result login(@Valid @RequestBody LoginDto loginUser, HttpServletResponse response)
    {
        int[] e[][] = new int[7][2][0];
        User user = userService.getOne(new QueryWrapper<User>().eq("username", loginUser.getUsername()));
       Assert.notNull(user,"用户名不存在");


        if(!loginUser.getPassword().equals(user.getPassword())){
            return new Result().fail("密码不正确");
        }

        if(user.getStatus()==2){
            return Result.fail("账号未激活");
        }

        String jwt = jwtUtils.generateToken(user.getId());


        response.setHeader("Authorization", jwt);
        response.setHeader("Access-control-Expose-Headers", "Authorization");

        return Result.succ(MapUtil.builder()
                .put("id", user.getId())
                .put("username", user.getUsername())
                .put("avatar",user.getAvatar())
                .put("name",user.getName())
                .map()
        );
    }

    //得到用户的详细信息
    @RequiresAuthentication
    @GetMapping("getUserDetail")
    public Result getUserDetail(@RequestParam  String username){
        User user = userService.getOne(new QueryWrapper<User>().eq("username", username));
        if(user==null){
            return Result.fail("请进行登录，才能获取信息");
        }
        return Result.succ(user);
    }

    //删除用户
    @GetMapping("deleteUser")
    public Result deleteUser(String id){
        userService.removeById(id);
        return Result.succ("成功删除");
    }

    //得到用户的详细信息
    @RequiresAuthentication
    @GetMapping("autoLogin")
    public Result autoLogin(String jwt){
        JwtToken token = new JwtToken(jwt);
        String userId = jwtUtils.getClaimByToken((String) token.getPrincipal()).getSubject();

        User user = userService.getOne(new QueryWrapper<User>().eq("id", userId));
        if(user==null){
            return Result.fail("请进行登录，才能获取信息");
        }
        return Result.succ(MapUtil.builder()
                .put("id", user.getId())
                .put("username", user.getUsername())
                .put("avatar",user.getAvatar())
                .put("name",user.getName())
                .put("status",user.getStatus())
                .map()
        );
    }

    @GetMapping("getUserList")
    public Result getUserList(){
        List<User> userList = userService.list();
        return Result.succ(userList);
    }

    //修改用户的密码
    @RequiresAuthentication
    @PostMapping("alterPassword")
    public Result alterPassword(@RequestBody LoginDto newUserDto){
        User user = userService.getOne(new QueryWrapper<User>().eq("username", newUserDto.getUsername()));
        if(user==null){
            return Result.fail("修改失败");
        }
        if(!user.getPassword().equals(newUserDto.getOldpass())){
            return Result.fail("旧密码填写错误");
        }
        userService.alterPassword(newUserDto.getUsername(),newUserDto.getPassword());
        return Result.succ(user);
    }

    //修改用户
    @RequiresAuthentication
    @PostMapping("alterUser")
    public Result alterPassword(@RequestBody User newUser){
        userService.updateById(newUser);
        return Result.succ("修改成功");

    }

    //修改头像
    @RequiresAuthentication
    @PostMapping("alterAvatar")
    public Result alterAvatar(@RequestBody LoginDto newUser){

        userService.uploadAvatar(newUser.getUsername(),newUser.getAvatarname());
        return Result.succ("修改成功");

    }

    //修改用户
    @RequiresAuthentication
    @PostMapping("uploadAvatar")
    public Result uploadAvatar(HttpServletRequest request, HttpServletResponse resp){
        InputStream is;
        ServletOutputStream out;
        String key=null;


        boolean isSucc=true;
        try {
            Collection<Part> parts=request.getParts();
            Iterator<Part> iterator=parts.iterator();

            if(parts.size()!=1){
                return Result.fail("只能上传一张照片");
            }
                Part part = iterator.next();
                is = part.getInputStream();
                FileOutputStream  fos=null;
                try
                {
                    fos=new FileOutputStream("forum-web\\public\\avatar\\"+part.getSubmittedFileName());

                    byte[] buf=new byte[1024];

                    int len=0;

                    while((len=is.read(buf))!=-1)
                    {
                        fos.write(buf,0,len);
                    }

                } catch (Exception e)
                {
                    // TODO: handle exception
                    throw new RuntimeException("下载失败");
                }
                finally
                {
                    try
                    {
                        if(is!=null)
                            is.close();
                    } catch (Exception e2)
                    {
                        // TODO: handle exception
                        isSucc=false;
                        throw new RuntimeException("读取文件失败");


                    }
                    try
                    {
                        if(fos!=null)
                            fos.close();
                    } catch (Exception e2)
                    {
                        // TODO: handle exception
                        isSucc=false;
                        throw new RuntimeException("写入文件失败");
                    }
                }
                if(!isSucc){
                    return Result.fail("上传图片失败");
                }

String u ="/avatar/"+part.getSubmittedFileName();
                return Result.succ("/avatar/"+part.getSubmittedFileName());

        } catch (Exception e) {
            isSucc=false;
            e.printStackTrace();

        }
        return Result.fail("上传图片失败");

    }
    //注册
    @PostMapping("register")
    public Result register(@RequestBody User user)
    {
        User oldUser = userService.getOne(new QueryWrapper<User>().eq("username",user.getUsername()));
        User oldUser1 = userService.getOne(new QueryWrapper<User>().eq("name",user.getName()));

        if(oldUser!=null){
            return Result.fail("用户名已存在，请重新输入");
        }
        if(oldUser1!=null){
            return Result.fail("昵称已存在，请重新输入");
        }
        user.setStatus(2);
        userService.saveUser(user);
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("18738315767@163.com");
        message.setTo(user.getEmail());
        message.setSubject("账号激活");
        message.setText("<a href= 'http://localhost:8080/active/"+user.getId()+"'>点击激活</a>");
        javaMailSender.send(message);
        return Result.succ("请进行激活账号");
    }

    @GetMapping("active")
    public Result active(String id)
    {
        User user = userService.getById(id);
        user.setStatus(0);
        userService.updateById(user);
        return Result.succ("激活成功");
    }
    //登出
    @RequiresAuthentication
    @GetMapping("logout")
    public Result logout() {
        SecurityUtils.getSubject().logout();
        return Result.succ(null);
    }
}
